package main

import (
	"embed"
	"fmt"
	"io/fs"
	"log"
	"net/http"
	"path"
)

const wwwroot string = "static"

func init() {
}

//go:embed static/*
var local embed.FS

// 所有文件文本索引
var FileIndex map[string]string = make(map[string]string)

func main() {

	fsys, err := fs.Sub(local, wwwroot)
	if err != nil {
		panic(err)
	}
	mux := http.NewServeMux()

	mux.Handle("/", http.FileServer(http.FS(fsys)))
	imgfs := http.FileServer(http.Dir(path.Join(CurrentSetting.DataPath, ImageDirName)))
	mux.Handle("/images/", http.StripPrefix("/images/", imgfs))

	// /api 接口
	mux.HandleFunc("GET /api/settings", settings)      // 获取设置
	mux.HandleFunc("POST /api/settings", saveSettings) // 修改设置

	mux.HandleFunc("GET /api/items", itemsList)    // 文件夹列表
	mux.HandleFunc("POST /api/item", renameItem)   // 添加/重命名文件/文件夹
	mux.HandleFunc("DELETE /api/item", deleteItem) // 删除文件/文件夹
	// mux.HandleFunc("GET /api/files", fileList)

	mux.HandleFunc("GET /api/file", fileContent)        // 文件内容
	mux.HandleFunc("POST /api/file", updateFileContent) // 修改文件内容
	mux.HandleFunc("DELETE /api/image", deleteImage)    // 删除图片

	mux.HandleFunc("POST /api/upload", uploadHandler)       // 上传
	mux.HandleFunc("POST /api/encrypt", encryptFileContent) // 加密文件
	mux.HandleFunc("POST /api/decrypt", decryptFileContent) // 解密文件

	mux.HandleFunc("GET /api/pull", pullFromGit)     // 拉取git
	mux.HandleFunc("GET /api/commit", commitAll)     // 提交
	mux.HandleFunc("GET /api/push", pushGit)         // 推送
	mux.HandleFunc("GET /api/git-status", gitStatus) // 状态

	mux.HandleFunc("GET /api/search", handleSearchFile) // 文件索引搜索

	handler := corsMiddleware(mux)

	// 建立文件内容索引
	go buildFileContentIndex()

	// 设置监听的端口
	url := fmt.Sprintf(":%d", CurrentSetting.Port)
	log.Printf("Starting server on port %s", url)

	// 启动HTTP服务器
	if err := http.ListenAndServe(url, handler); err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 设置允许跨域的头部信息
		w.Header().Set("Access-Control-Allow-Origin", "*") // 允许所有域名访问，可以替换为具体的域名
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		// 如果是预检请求（OPTIONS 方法），直接返回 200
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusOK)
			return
		}

		// 调用下一个处理器
		next.ServeHTTP(w, r)
	})
}
